package com.prime;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

public class WrongIfPrimeChecker implements CanCheckIfPrime {

	private static final ConcurrentHashMap<Integer, AtomicReference<Boolean>> isPrimeCache = new ConcurrentHashMap<Integer, AtomicReference<Boolean>>();
	
	@Override
	public final boolean isPrime(int number) {
		AtomicReference<Boolean> val = isPrimeCache.get(number);
		if(val != null){
			if (val.get() == null){//to avoid NPEs ;)
				new RuntimeException().printStackTrace();
				System.exit(1);
			}
			return val.get();
		}
		isPrimeCache.putIfAbsent(number, new AtomicReference<Boolean>());
		val = isPrimeCache.get(number);
		/* Do other stuff */
		int sqrt = (int) Math.sqrt(number) + 1;
        for (int i = 2; i < sqrt; i++) {
            if (number % i == 0) {
                val.set(false);
            	return val.get();
            }
        }
        val.set(true);
    	return val.get();
	}

	public static void main(String[] args) {
		Runnable r = new Runnable() {
			@Override
			public void run() {
				WrongIfPrimeChecker checker = new WrongIfPrimeChecker();
				for(int i = Integer.MAX_VALUE; i > 2; i --){
					checker.isPrime(i);
				}
			}
		};
		Thread t1 = new Thread(r), t2 = new Thread(r);
		t1.start();
		t2.start();
	}
	
}
